<template>
  <div class="backend-layout">
    <el-container class="container">
      <!-- 侧边栏 -->
      <el-aside width="230px" class="sidebar">
        <div class="logo-container" @click="$router.push('/home')">
          <img src="@/assets/img/logo.png" alt="博物馆文创" class="logo-img" />
          <h2 class="logo-text">博物馆文创</h2>
        </div>
        
        <el-menu
          default-active="1"
          class="el-menu-vertical"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          unique-opened
          router
        >
          <el-sub-menu index="1">
            <template #title>
              <el-icon><ShoppingBag /></el-icon>
              <span>商品管理</span>
            </template>
            <el-menu-item index="/home/products">商品列表</el-menu-item>
            <el-menu-item index="/home/add">添加商品</el-menu-item>
            <el-menu-item index="/home/comments">商品评价</el-menu-item>
          </el-sub-menu>
          
          <el-sub-menu index="2">
            <template #title>
              <el-icon><Document /></el-icon>
              <span>订单管理</span>
            </template>
            <el-menu-item index="/home/orders">订单列表</el-menu-item>
            <el-menu-item index="/home/orders/pending">待处理订单</el-menu-item>
            <el-menu-item index="/home/orders/shipping">配送中订单</el-menu-item>
            <el-menu-item index="/home/orders/completed">已完成订单</el-menu-item>
          </el-sub-menu>
          
          <el-sub-menu index="3">
            <template #title>
              <el-icon><ChatLineRound /></el-icon>
              <span>文化资讯管理</span>
            </template>
            <el-menu-item index="/home/cultural-info">资讯列表</el-menu-item>
            <el-menu-item index="/home/add-cultural-info">添加文化资讯</el-menu-item>
          </el-sub-menu>
          
          <!-- <el-sub-menu index="4">
            <template #title>
              <el-icon><PieChart /></el-icon>
              <span>统计分析</span>
            </template>
            <el-menu-item index="/home/dashboard">数据概览</el-menu-item>
            <el-menu-item index="/home/sales">销售统计</el-menu-item>
          </el-sub-menu>
          
          <el-sub-menu index="5">
            <template #title>
              <el-icon><Setting /></el-icon>
              <span>系统设置</span>
            </template>
            <el-menu-item index="/home/settings">基本设置</el-menu-item>
            <el-menu-item index="/home/backup">数据备份</el-menu-item>
          </el-sub-menu> -->
        </el-menu>
      </el-aside>
      
      <!-- 主内容区 -->
      <el-container class="main-container">
        <!-- 顶部导航 -->
        <el-header height="70px" class="header">
          <div class="header-left">
            <el-icon class="collapse-btn" @click="isCollapse = !isCollapse">
              <Menu />
            </el-icon>
            <breadcrumb class="breadcrumb" />
          </div>
          
          <div class="header-right">
            <el-dropdown trigger="click">
              <div class="user-info">
                <!-- <img src="@/assets/img/avatar.png" class="user-avatar" /> -->
                <span class="user-name">管理员</span>
                <el-icon><ArrowDown /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>个人信息</el-dropdown-item>
                  <el-dropdown-item>修改密码</el-dropdown-item>
                  <el-dropdown-item  @click="layout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <!-- 内容区 -->
        <el-main class="main-content">
          <!-- 使用router-view来展示子路由内容 -->
          <router-view v-slot="{ Component }">
            <component :is="Component" v-if="Component" />
            <!-- 当没有匹配到子路由时，显示默认的仪表盘内容 -->
            <template v-else>
              <el-row :gutter="20" class="dashboard-summary">
                <!-- 总销售额 -->
                <el-col :span="6">
                  <el-card shadow="hover" class="data-card">
                    <template #header>
                      <div class="card-header">
                        <span>总销售额</span>
                        <el-tooltip content="最近30天销售总额" placement="top">
                          <el-icon><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </div>
                    </template>
                    <div class="card-content">
                      <span class="card-value">¥ {{ dashboardStats.totalSales?.toLocaleString() || '0' }}</span>
                    </div>
                  </el-card>
                </el-col>
                
                <!-- 总订单数 -->
                <el-col :span="6">
                  <el-card shadow="hover" class="data-card">
                    <template #header>
                      <div class="card-header">
                        <span>总订单数</span>
                        <el-tooltip content="最近30天订单总数" placement="top">
                          <el-icon><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </div>
                    </template>
                    <div class="card-content">
                      <span class="card-value">{{ dashboardStats.totalOrders?.toLocaleString() || '0' }}</span>
                    </div>
                  </el-card>
                </el-col>
                
                <!-- 新增用户 -->
                <el-col :span="6">
                  <el-card shadow="hover" class="data-card">
                    <template #header>
                      <div class="card-header">
                        <span>新增用户</span>
                        <el-tooltip content="最近30天新增用户数" placement="top">
                          <el-icon><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </div>
                    </template>
                    <div class="card-content">
                      <span class="card-value">{{ dashboardStats.newUsers?.toLocaleString() || '0' }}</span>
                    </div>
                  </el-card>
                </el-col>
                
                <!-- 商品总数 -->
                <el-col :span="6">
                  <el-card shadow="hover" class="data-card">
                    <template #header>
                      <div class="card-header">
                        <span>商品总数</span>
                        <el-tooltip content="当前上架商品总数" placement="top">
                          <el-icon><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </div>
                    </template>
                    <div class="card-content">
                      <span class="card-value">{{ dashboardStats.totalProducts?.toLocaleString() || '0' }}</span>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
              
              <!-- 商品销售排行 -->
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-card class="product-ranking" shadow="hover">
                    <template #header>
                      <div class="card-title">
                        <span>商品销售排行</span>
                        <el-radio-group v-model="timeRange" size="small">
                          <el-radio-button label="week">本周</el-radio-button>
                          <el-radio-button label="month">本月</el-radio-button>
                          <el-radio-button label="year">全年</el-radio-button>
                        </el-radio-group>
                      </div>
                    </template>
                    <el-table :data="topProducts" stripe style="width: 100%" v-loading="productRankingLoading">
                      <el-table-column type="index" label="排名" width="80" />
                      <el-table-column prop="name" label="商品名称" />
                      <el-table-column prop="category" label="分类" width="120" />
                      <el-table-column prop="sales" label="销量" width="120" />
                      <el-table-column prop="amount" label="销售额" width="120" />
                      <el-table-column label="趋势" width="180">
                        <template #default="scope">
                          <div class="trend-column">
                            <span :class="['trend', scope.row.trendType]">{{ scope.row.trend }}</span>
                            <el-progress 
                              :percentage="scope.row.percentage" 
                              :color="scope.row.trendType === 'up' ? '#67C23A' : '#F56C6C'"
                            />
                          </div>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-card>
                </el-col>
              </el-row>
              
              <!-- 待处理订单 -->
              <el-card class="recent-orders" shadow="hover">
                <template #header>
                  <div class="card-title">
                    <span>待处理订单</span>
                    <el-button type="primary" size="small" text @click="$router.push('home/orders/pending')">查看全部</el-button>
                  </div>
                </template>
                <el-table :data="pendingOrders" stripe style="width: 100%" v-loading="ordersLoading">
                  <el-table-column prop="number" label="订单号" width="180" />
                  <el-table-column prop="userName" label="客户名称" width="120" />
                  <el-table-column prop="totalAmount" label="订单金额" width="120">
                    <template #default="scope">
                      <span>¥{{ scope.row.totalAmount.toFixed(2) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态">
                    <template #default="scope">
                      <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createTime" label="创建时间" width="180" />
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button type="primary" size="small" @click="handleOrder(scope.row)">处理</el-button>
                      <el-button type="info" size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </template>
          </router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { 
  ShoppingBag, 
  Document, 
  User, 
  PieChart, 
  Setting,
  Menu,
  ArrowDown,
  QuestionFilled
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import * as api from '@/assets/js/api';

const router = useRouter();

// 侧边栏折叠状态
const isCollapse = ref(false);

// 时间范围选择
const timeRange = ref('month');

// 统计数据
const dashboardStats = ref({
  totalSales: 0,
  salesGrowth: 0,
  totalOrders: 0,
  ordersGrowth: 0,
  newUsers: 0,
  usersGrowth: 0,
  totalProducts: 0,
  productsGrowth: 0
});

// 待处理订单数据
const pendingOrders = ref([]);
const ordersLoading = ref(false);

// 商品销售排行数据
const topProducts = ref([]);
const productRankingLoading = ref(false);

// 获取仪表盘统计数据
const getDashboardData = async () => {
  try {
    const response = await api.getDashboardStatistics(30);
    if (response.code === 200 && response.data) {
      dashboardStats.value = response.data;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ElMessage.error('获取仪表盘统计数据失败');
  }
};

// 获取待处理订单数据
const getPendingOrders = async () => {
  ordersLoading.value = true;
  try {
    // 构建查询参数，只查询待处理状态订单的前5条
    const params = {
      page: 1,
      pageSize: 5,
      status: 'paid'
    };
    
    const response = await api.getAllOrders(params);
    pendingOrders.value = response.data.records || [];
  } catch (error) {
    console.error('获取待处理订单失败:', error);
    ElMessage.error('获取待处理订单数据失败');
  } finally {
    ordersLoading.value = false;
  }
};

// 获取商品销售排行
const getProductRankingData = async () => {
  productRankingLoading.value = true;
  try {
    const response = await api.getProductRanking(timeRange.value);
    if (response.code === 200 && response.data) {
      topProducts.value = response.data;
    }
  } catch (error) {
    console.error('获取商品销售排行失败:', error);
    ElMessage.error('获取商品销售排行数据失败');
  } finally {
    productRankingLoading.value = false;
  }
};

// 监听时间范围变化，重新获取销售排行数据
watch(timeRange, () => {
  getProductRankingData();
});

// 页面加载时获取数据
onMounted(() => {
  getDashboardData();
  getPendingOrders();
  getProductRankingData();
});

// 获取订单状态对应的类型
const getStatusType = (status) => {
  const statusMap = {
    'unpaid': 'warning',     // 待付款
    'paid': 'success',       // 已付款
    'pending': 'primary',    // 待处理
    'shipping': 'info',      // 配送中
    'completed': 'success',  // 已完成
    'cancelled': 'danger',   // 已取消
  };
  return statusMap[status] || 'info';
};

// 获取订单状态对应的文本
const getStatusText = (status) => {
  const statusMap = {
    'unpaid': '待付款',
    'paid': '已付款',
    'pending': '待处理',
    'shipping': '配送中',
    'completed': '已完成',
    'cancelled': '已取消',
  };
  return statusMap[status] || '未知状态';
};

// 处理订单
const handleOrder = (order) => {
  ElMessageBox.confirm(`确定要处理订单 ${order.number} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 导航到订单详情页进行处理
    router.push(`/backend/orders?number=${order.number}`);
  }).catch(() => {});
};

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push(`/backend/orders?number=${order.number}`);
};

const layout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    router.push('/');
  }).catch(() => {});
};
</script>

<style scoped>
@import '@/assets/css/backHome.css'
</style>
